import { ElMessage } from 'element-plus'

import router from '@/router'

import packageFile from '../../package.json'
import { getToken, removeAll, removeToken } from './auth'
import axios from 'axios'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API as string,
  timeout: 10000 * 6, // request timeout
})

// 发起请求之前的拦截器
service.interceptors.request.use(
  (config: any) => {
    // 如果有token 就携带tokon
    // const token = getToken()
    // if (token) {
    //   config.headers['Authorization'] = 'Bearer__' + token
    // }
    return config
  },
  (error: any) => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
  (response: any) => {
    const firstStatus = response.status
    const config = response.config
    const firData = response.data
    const { status, data, message, code } = firData

    if (firstStatus === 200) {
      if (firData instanceof ArrayBuffer) {
        // 报表类型
        return response
      }

      // 如果只返回 data
      if (config.onlyData) {
        if (status === 200) {
          return data
        }
        if (code === 'A0312' || code === 'A0230') {
          // token失效
          ElMessage.closeAll()
          ElMessage({
            type: 'error',
            message: 'token已失效，将退出登录！',
          })
          removeAll()
          setTimeout(() => {
            // ElMessage.closeAll()
            // removeAll()
            // router.push('/login')
            window.location.reload()
          }, 1000)
        } else if (code !== 204) {
          ElMessage({
            type: 'error',
            message,
          })
        }
        return null
      }
      if (status === 200) {
        return firData
      }
      if (code === 'A0312' || code === 'A0230') {
        // token失效
        ElMessage.closeAll()
        ElMessage({
          type: 'error',
          message: 'token已失效，将退出登录！',
        })
        removeAll()
        setTimeout(() => {
          // removeAll()
          window.location.reload()
          // ElMessage.closeAll()
          // removeAll()
          // router.push('/login')
        }, 1000)
      } else if (code !== 204) {
        ElMessage({
          type: 'error',
          message,
        })
      }

      return firData
    }
    ElMessage({
      type: 'error',
      message: '服务器内部错误！',
    })

    // return firData
  },
  (error: any) => {
    console.log('e', error, error.response.status)
    if (error.response && error.response.status === 401) {
      removeToken()
      location.reload()
    }
    // token失效
    if (error.response && error.response.status === 403) {
      console.log(22)
      removeToken()
      location.reload()
    }
    ElMessage({
      type: 'error',
      message: error.message,
    })
    return Promise.reject(error)
  }
)

// 封装axiosRequest
const axiosRequest = (
  option: { url: string; method: string; [key: string]: any },
  onlyData = false
) => {
  const config: any = { ...option, onlyData }
  config.method === undefined && (config.method = 'post')
  const baseToken: any = import.meta.env.VITE_APP_BASE_TOKEN

  // 公共请求头
  const baseHeaders = {
    [baseToken]: getToken(),
    // 'LOGIN-USER-UID': store.getters.uid || null,
    // 'LOGIN-USER-KEY': store.getters.loginCode || null,
    version: packageFile.version,
  }
  // 添加公共请求头
  config.headers = Object.assign({}, baseHeaders, config.headers)

  return service.request(config)
}

export default axiosRequest
